#[macro_use] extern crate fluffy;

use actix_web::{web, App, HttpServer};
use fluffy::{cache, db, middlewares};

mod common;
mod models;
mod validations;
mod controllers;

use common::{REDIS_CONN_STR, MYSQL_CONN_STR};
use controllers::{index, users};

const BIND_ADDR: &str = "127.0.0.1:8091"; //監聽主機地址
const REQUEST_HOST: &str = "http://127.0.0.1:8092"; //客戶端請求主機地址

/// 主程序
#[actix_rt::main]
async fn main() -> std::io::Result<()> {

    db::init_connections(MYSQL_CONN_STR); //连接数据库
    cache::init_connections(REDIS_CONN_STR); //连接缓存
    common::caches::init_user_keys();
    println!("监听地址端口: http://{}", BIND_ADDR);

    HttpServer::new(||
        App::new()
            .wrap(cors!(REQUEST_HOST))
            //.service(web::resource("/{url}").to(index::short_url))
            .service(
                web::scope("/v1")
                    .service(web::resource("/").to(index::index))
                    .service(web::resource("/trans").route(web::post().to(index::trans)))
                    .service(web::resource("/index").to(index::index))
                    .service(web::resource("/index/login").route(web::post().to(index::login)))
                    .service(web::resource("/index/register").route(web::post().to(index::register)))
                    .service(web::resource("/url/{code}").to(index::short_url))
                    .service(
                        web::scope("/auth")
                            .wrap(middlewares::auth::Authentication)
                            .service(web::resource("/users/index").to(users::index))
                            .service(web::resource("/users/dev").to(users::dev))
                            .service(web::resource("/users/links").to(users::links))
                            .service(web::resource("/users/logout").to(users::logout))
                    )
            )
    )
    .bind(BIND_ADDR)?
    .run()
    .await
}
